//
//  KQMessageVoiceContentView.swift
//  JChat
//
//  Created by JIGUANG on 2017/3/9.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import AVFoundation
import KQChatSDK
import KQToast
import KQGeneric

open class KQMessageVoiceContentView: UIView, KQMessageContentViewType {
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        _commonInit()
    }
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        _commonInit()
    }
    
    deinit {
        KQAudioPlayerHelper.sharedInstance.stopAudio()
    }

    
    open func apply(_ message: KQMessageType) {
        guard let content = message.jmessage?.content as? WFCCSoundMessageContent else {
            return
        }
        guard let voiceContent = message.content as? KQMessageVoiceContent else {
            return
        }
        voiceContent.duration = TimeInterval(content.duration)
        voiceContent.data = content.getWavData()
        _duration = Double(content.duration)
        _message = message
        _delegate = voiceContent.delegate
        _updateViewLayouts(message.options)
        _data = content.getWavData()
        
        _titleLabel.attributedText = voiceContent.attributedText
    }
    
    private func _updateViewLayouts(_ options: KQMessageOptions) {
        guard _alignment != options.alignment else {
            return
        }
        _alignment = options.alignment
        
        if _alignment == .left {
            _titleLabel.textColor = UIColor.black
            _titleLabel.textAlignment = .left
            _animationView.image = UIImage.loadImage("chat_voice_receive_icon_3")
            _animationView.animationImages = [
                UIImage.loadImage("chat_voice_receive_icon_1"),
                UIImage.loadImage("chat_voice_receive_icon_2"),
                UIImage.loadImage("chat_voice_receive_icon_3"),
            ].compactMap { $0 }
            
            _animationView.snp.remakeConstraints { (make) in
                make.left.equalToSuperview()
                make.centerY.equalToSuperview()
                make.width.equalTo(15)
                make.height.equalTo(15)
            }
            _titleLabel.snp.remakeConstraints { (make) in
                make.left.equalTo(_animationView.snp.right).offset(8)
                make.centerY.equalToSuperview()
                make.height.equalTo(15)
            }
            
        } else {
            _titleLabel.textColor = UIColor.black
            _titleLabel.textAlignment = .right
            _animationView.image = UIImage.loadImage("chat_voice_send_icon_3")
            _animationView.animationImages = [
                UIImage.loadImage("chat_voice_send_icon_1"),
                UIImage.loadImage("chat_voice_send_icon_2"),
                UIImage.loadImage("chat_voice_send_icon_3"),
            ].compactMap { $0 }
            
            _animationView.snp.remakeConstraints { (make) in
                make.right.equalToSuperview()
                make.centerY.equalToSuperview()
                make.width.equalTo(15)
                make.height.equalTo(15)
            }
            _titleLabel.snp.remakeConstraints { (make) in
                make.right.equalTo(_animationView.snp.left).offset(-8)
                make.centerY.equalToSuperview()
                make.height.equalTo(15)
            }
            
        }
    }
    
    private func _commonInit() {
        _animationView.animationDuration = 0.8
        _animationView.animationRepeatCount = 0
        addSubview(_animationView)
        addSubview(_titleLabel)
        
        _animationView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(15)
            make.height.equalTo(15)
        }
        _titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(_animationView.snp.right).offset(8)
            make.centerY.equalTo(0)
            make.height.equalTo(15)
        }
        _tapGesture()
    }
    
    func _tapGesture() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(_clickCell))
        tap.numberOfTapsRequired = 1
        addGestureRecognizer(tap)
    }
    
    @objc func _clickCell() {
        let soundContent = _message.jmessage?.content as? WFCCSoundMessageContent

        if soundContent?.localPath.count == 0 || !WFCUUtilities.isFileExist(soundContent?.localPath) {
            WFCUMediaMessageDownloader.shared().tryDownload(_message.jmessage) { [weak self] messageUid, localPath in
                KQAudioPlayerHelper.sharedInstance.delegate = self
                self?._delegate?.message?(message: (self?._message)!, voiceData: soundContent?.getWavData(), duration: self?._duration ?? 0)
                
                self?._animationView.startAnimating()
                if KQAudioPlayerHelper.sharedInstance.player.isPlaying == false {
                    self?._animationView.stopAnimating()
                }
            } error: { messageUid, error_code in
                KQToast.show("播放失败",duration: 1)
            }
        } else {
            _delegate?.message?(message: _message, voiceData: soundContent?.getWavData(), duration: _duration)
            KQAudioPlayerHelper.sharedInstance.delegate = self
            _animationView.startAnimating()
            if KQAudioPlayerHelper.sharedInstance.player.isPlaying == false {
                _animationView.stopAnimating()
            }
        }
        
        
    }

    private var _duration: Double = 0.0
    private weak var _delegate: KQMessageDelegate?
    private var _message: KQMessageType!
    fileprivate lazy var _animationView: UIImageView = UIImageView()
    private lazy var _titleLabel: UILabel = UILabel()
    private var _data: Data?
    private var _alignment: KQMessageAlignment = .center
}

extension KQMessageVoiceContentView: KQAudioPlayerHelperDelegate {
    func didAudioPlayerStopPlay(_ AudioPlayer: AVAudioPlayer) {
        _animationView.stopAnimating()
    }
    func didAudioPlayerBeginPlay(_ AudioPlayer: AVAudioPlayer) {
        
    }
    func didAudioPlayerPausePlay(_ AudioPlayer: AVAudioPlayer) {
        _animationView.stopAnimating()
    }
}
